import React, { Suspense, useRef, useState } from 'react'
import { 
  Html, 
  useTexture, 
  Edges,
  Trail
 } from '@react-three/drei'
import { useSpring, animated, config } from '@react-spring/three'
import * as THREE from 'three';
import { Canvas, useFrame, useLoader, useThree, extend } from '@react-three/fiber'


export function EdgesBox({...props}) {
  return <Trail
    width={0.2} // Width of the line
    color={'hotpink'} // Color of the line
    length={1} // Length of the line
    decay={1} // How fast the line fades away
    local={false} // Wether to use the target's world or local positions
    stride={0} // Min distance between previous and current point
    interval={1} // Number of frames to wait before next calculation
    target={undefined} // Optional target. This object will produce the trail.
    attenuation={(width) => width} // A function to define the width in each point along it.
  >
    <mesh {...props}>
      <meshBasicMaterial color={0x3399ee} />
      <boxGeometry />
      <Edges
        linewidth={2}
        scale={1.05}
        threshold={15} // Display edges only when the angle between two faces exceeds this value (default=15 degrees)
        color="white"
      />
    </mesh>
  </Trail>
  
}




export function Stone() {
  // 材质
  const mapProps = useTexture({
    map: '/PavingStones/Color.jpg',
    aoMap: '/PavingStones/AmbientOcclusion.jpg',
    displacementMap: '/PavingStones/Displacement.jpg',
    normalMap: '/PavingStones/NormalGL.jpg',
    roughnessMap: '/PavingStones/Roughness.jpg',
  });

  // 动画
  const [active, setActive] = useState(false);
  const {scale} = useSpring({
    scale: active ? 1.5: 1,
    config: config.wobbly // ease
  });

  return <Suspense fallback={<Html><h1>YO</h1></Html>}>
    <animated.mesh onClick={() => setActive(!active)} scale={scale}>
      <sphereGeometry />
      <meshStandardMaterial {...mapProps} displacementScale={.2} />
    </animated.mesh>
  </Suspense>
}

export function Points() {
  const v = new Float32Array([
    1, 1, 1,
    2, 2, 2,
    3, 3, 3
  ])
  const refAttr = useRef();

  // useEffect(() => {
  //   console.log('refAttr', refAttr.current)
  // }, [])

  // const camera = useThree(state => state.size)
  return <points 
    onClick={e => {
      console.log('click', e)
      e.stopPropagation()
    }}
  >
    <bufferGeometry>
      <bufferAttribute ref={refAttr} attach="attributes-position" array={v} count={v.length / 3} itemSize={3}></bufferAttribute>
    </bufferGeometry>
    <pointsMaterial color={0x339933} size={1}></pointsMaterial>
  </points>
}
